package zy.service.sell.shift.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.sell.shift.ShiftDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.sell.shift.T_Sell_Shift;
import zy.service.sell.shift.ShiftService;
import zy.util.CommonUtil;
import zy.util.StringUtil;

@Service
public class ShiftServiceImpl implements ShiftService{
	@Resource
	private ShiftDAO shiftDAO;

	@Override
	public PageData<T_Sell_Shift> page(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = shiftDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<T_Sell_Shift> list = shiftDAO.list(params);
		PageData<T_Sell_Shift> pageData = new PageData<T_Sell_Shift>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}

	@Override
	public List<T_Sell_Shift> listShop(Map<String, Object> param) {
		return shiftDAO.listShop(param);
	}

	@Override
	public T_Sell_Shift queryByID(Integer st_id) {
		return shiftDAO.queryByID(st_id);
	}

	@Override
	@Transactional
	public void save(T_Sell_Shift shift) {
		String st_shop_code = shift.getSt_shop_code();
		if (StringUtil.isEmpty(st_shop_code)) {
			throw new IllegalArgumentException("店铺不能为空!");
		}
		Integer companyid = shift.getCompanyid();
		//获取班次最大code
		String max_st_code = shiftDAO.queryMaxStcode(companyid);
		Integer int_st_code = Integer.parseInt(max_st_code);
		
		String[] st_shop_codes = st_shop_code.split(",");
		List<T_Sell_Shift> shifts = new ArrayList<T_Sell_Shift>();
		T_Sell_Shift t_Sell_Shift = null;
		for(int i=0;i<st_shop_codes.length;i++){
			t_Sell_Shift = new T_Sell_Shift();
			t_Sell_Shift.setSt_code(StringUtil.getTwoCode(int_st_code + i));
			t_Sell_Shift.setSt_name(shift.getSt_name());
			t_Sell_Shift.setSt_shop_code(st_shop_codes[i]);
			t_Sell_Shift.setSt_begintime(shift.getSt_begintime());
			t_Sell_Shift.setSt_endtime(shift.getSt_endtime());
			t_Sell_Shift.setCompanyid(shift.getCompanyid());
			shifts.add(t_Sell_Shift);
		}
		
		shiftDAO.save(shifts);
	}

	@Override
	public void update(T_Sell_Shift shift) {
		shiftDAO.update(shift);
	}

	@Override
	public void del(Integer st_id) {
		shiftDAO.del(st_id);
	}
}
